/*
 * This file is part of TradeHelper library.
 *
 * TradeHelper library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * TradeHelper library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with TradeHelper library.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.rag.assistants;

import com.alee.laf.WebLookAndFeel;
import com.alee.utils.FileUtils;
import com.alee.utils.XmlUtils;
import com.alee.utils.collection.ValuesTable;
import com.rag.core.Item;
import com.rag.core.RagData;
import com.rag.managers.BaseManager;
import com.rag.managers.RagManager;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

import java.io.IOException;
import java.net.URL;

/**
 * User: mgarin Date: 15.06.12 Time: 16:12
 */

public class IroWikiDescriptionLoader
{
    private static String descriptionClass = "bgLtRow1 padded";

    private static int startId = 0;
    private static int threadsCount = 64;

    private static RagData ragData;
    private static ValuesTable<String, Item> known;

    public static void main ( String[] args )
    {
        WebLookAndFeel.install ();
        BaseManager.initialize ();
        RagManager.initialize ();

        // Получаем текущие данные
        ragData = RagManager.getRagData ();
        known = RagManager.getKnownItems ();

        // Запускаем потоки обработки
        for ( int thread = 0; thread < threadsCount; thread++ )
        {
            startThread ( thread );
        }

        // Добавляем слушатель завершения JVM (когда все потоки завершатся он будет вызван автоматом)
        Runtime.getRuntime ().addShutdownHook ( new Thread ( new Runnable ()
        {
            public void run ()
            {
                System.out.println ();
                System.out.println ( "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" );
                System.out.println ( "=-=-=-=- Saving result and exiting -=-=-=-=" );
                System.out.println ( "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" );

                ragData.setItems ( known.getValues () );
                XmlUtils.toXML ( ragData, "remote/data.xml" );
            }
        } ) );
    }

    private static void startThread ( final int thread )
    {
        new Thread ( new Runnable ()
        {
            public void run ()
            {
                for ( int i = thread; i < known.size (); i += threadsCount )
                {
                    if ( i < known.size () )
                    {
                        updateItem ( known.get ( i ) );
                    }
                }
            }
        } ).start ();
    }

    private static void updateItem ( Item item )
    {
        // Загружаем страницу
        String itemPage = loadItemPage ( item );
        if ( itemPage != null )
        {
            // Выцепляем со страницы описание
            Source itemPageSource = new Source ( itemPage );
            itemPageSource.fullSequentialParse ();
            for ( Element element : itemPageSource.getAllElements ( HTMLElementName.TD ) )
            {
                String classValue = element.getAttributeValue ( "class" );
                if ( classValue != null && classValue.equals ( descriptionClass ) )
                {
                    String description = element.getContent ().toString ();
                    parseDescription ( item, description );
                    break;
                }
            }

            // Заменяем ссылки полными версиями для корректно работы WebEditorPane
            String iro = item.getIroDescription ();
            if ( iro != null )
            {
                item.setIroDescription ( iro.replaceAll ( "/db/item-info/",
                        "http://db.irowiki.org/db/item-info/" ) );
            }
        }
    }

    private static synchronized void parseDescription ( Item item, String description )
    {
        if ( !description.contains ( "The item wasn't found in the database." ) )
        {
            item.setIroDescription ( description );
            System.out.println ( "Item " + item + " (" + item.getId () + ") was updated" );
        }
        else
        {
            System.out.println ( "Item " + item + " (" + item.getId () + ") was not found" );
        }
    }


    private static String loadItemPage ( Item item )
    {
        try
        {
            URL url = new URL ( item.getIroLink () );
            return FileUtils.readToString ( url.openStream () );
        }
        catch ( IOException e )
        {
            return null;
        }
    }
}